package com.asiainfo.rsa;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * RSA签名验签类
 */
public class RSASignature {

    private static Logger log = LoggerFactory.getLogger(RSASignature.class);

    /**
     * 签名算法
     */
    public static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    /**
     * RSA签名
     *
     * @param content 待签名数据
     * @param privateKey 商户私钥
     * @param encode 字符集编码
     * @return 签名值
     */
    public static String sign(String content, String privateKey, String encode) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyFactory.generatePrivate(priPKCS8);

            java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);

            signature.initSign(priKey);
            signature.update(content.getBytes(encode));

            byte[] signed = signature.sign();

            return Base64.encodeBase64String(signed);
        } catch (Exception e) {
            log.error("签名异常！",e);
        }

        return null;
    }

    public static String sign(String content, String privateKey) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyFactory.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(content.getBytes("UTF-8"));
            byte[] signed = signature.sign();
            return Base64.encodeBase64String(signed);
        } catch (Exception e) {
            log.error("签名异常！",e);
        }
        return null;
    }

    /**
     * RSA验签名检查
     *
     * @param content 待签名数据
     * @param sign 签名值
     * @param publicKey 分配给开发商公钥
     * @param encode 字符集编码
     * @return 布尔值
     */
    public static boolean doCheck(String content, String sign, String publicKey, String encode) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decodeBase64(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);

            signature.initVerify(pubKey);
            signature.update(content.getBytes(encode));

            return signature.verify(Base64.decodeBase64(sign));

        } catch (Exception e) {
            log.error("验证签名异常！",e);
        }

        return false;
    }

    public static boolean doCheck(String content, String sign, String publicKey) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decodeBase64(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);

            signature.initVerify(pubKey);
            signature.update(content.getBytes("UTF-8"));

            return signature.verify(Base64.decodeBase64(sign));

        } catch (Exception e) {
            log.error("验证签名异常！",e);
        }

        return false;
    }

    public static void main(String[] args) {
        String content = "account=xxxx&activeTime=xxxx&authorizeTime=xxxx&auzCertificate=xxxx&encryptContent=xxxx&encryption=1&passWord=xxxx&versionNo=1.0.0";
        String priKey = IOUtil.loadKeyByFile("E:\\abc\\privateKey.keystore");
        String re = sign(content, priKey);
        System.out.println(re);

        String si = "IEZlxw4V1wYWSBo23H2zJJRek3fuTzZVctsf1+CPG7pFfrE8AOyIeDywCLeRRHE903mi2gDjeh0iA+XBEBdLDmD4eEnK/WLo0xr7snkLgoFaniN5Uj358UPy2M8zZH36OGBr6rtR8ljYS8kWOyTqCzY4SwkNTtcykg6tpV4n64Y=";
        String pubKey = IOUtil.loadKeyByFile("E:\\abc\\publicKey.keystore");
        boolean checkRe = doCheck(content, si, pubKey);
        System.out.println(checkRe);
    }

}
